package com.rgsx.config;

import com.alibaba.fastjson.JSON;
import com.rgsx.utils.JWTUtil;
import com.rgsx.vo.ResultVo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        response.setHeader("Access-Control-Allow-Origin"
                , "*");// 允许指定域访问跨域资源
        //是否允许cookie
        //response.setHeader("Access-Control-Allow-Credentials", "true");     //
        response.setHeader("Access-Control-Allow-Methods"
                , "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age"
                , "18000");//Access-Controld-Max-Age用来指定本次预检请求的有效期，单位为秒，，在此期间不用发出另一条预检请求。
        response.setHeader("Access-Control-Allow-Headers"
                , "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,Access-Token,token-header");
        response.setHeader("Access-Control-Expose-Headers", "*");//响应客户端的头部 允许携带Token 等等
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        if(JWTUtil.verify(token)){
            return true;
        }else {
            response.getWriter().write(JSON.toJSONString(ResultVo.fail("登陆过期","-1")));
            return false;
        }
    }
}
